package com.egao.common.module.system.transfer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.company.constants.CheckRecordConstants;
import com.egao.common.module.company.entity.*;
import com.egao.common.module.company.service.*;
import com.egao.common.module.push.entity.PositionMatching;
import com.egao.common.module.push.service.PositionMatchingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 单位数据导入
 * @author: dl
 */
@RestController
@Slf4j
public class PreachCloudDataController {

    @Value("${old.datasource.jyurl}")
    private String url;

    @Value("${old.datasource.username}")
    private String userName;

    @Value("${old.datasource.password}")
    private String password;

    @Value("${minio.old-data-head}")
    private String contentUrl;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private PreachCloudService preachCloudService;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult transfer() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        long beginTime = System.currentTimeMillis();
        List<Company> companyList = getCompanyList();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, userName, password);
            st = conn.createStatement();
            String sql = "SELECT " +
                    " id, " +
                    " companyid, " +
                    " title, " +
                    " sponsor, " +
                    " holdurl, " +
                    " holddate, " +
                    " COMMENT, " +
                    " hits, " +
                    " recruitnumber, " +
                    " jobname, " +
                    " major, " +
                    " education, " +
                    " email, " +
                    " tel, " +
                    " recruiturl, " +
                    " linkman, " +
                    " auditor, " +
                    " ip, " +
                    " liabletel, " +
                    " personliable, " +
                    " cancel, " +
                    " checkstate, " +
                    " checkcomment, " +
                    " checktime, " +
                    " checkuserid, " +
                    " create_date, " +
                    " create_by, " +
                    " update_date, " +
                    " update_by, " +
                    " remarks, " +
                    " del_flag, " +
                    " salary, " +
                    " work_place " +
                    " FROM " +
                    " preach_cloud";
            st = conn.createStatement();
            rs = st.executeQuery(sql);
            log.info("总数：{}", rs.getRow());
            int i = 0;
            while (rs.next()) {
                String oldId = rs.getString("id");
                String companyid = rs.getString("companyid");
                String title = rs.getString("title");
                String companyName = rs.getString("sponsor");

                Date holddate = rs.getTimestamp("holddate") != null ? new Date(rs.getTimestamp("holddate").getTime()) : null;
                String holdurl = rs.getString("holdurl");
                String comment = rs.getString("COMMENT");
                Integer hits = rs.getInt("hits");
                String recruitnumber = rs.getString("recruitnumber");
                String jobname = rs.getString("jobname");
                String majors = rs.getString("major");
                String education = rs.getString("education");
                String email = rs.getString("email");
                String tel = rs.getString("tel");
                String recruiturl = rs.getString("recruiturl");
                String linkman = rs.getString("linkman");
                Integer cancel = rs.getInt("cancel");
                String salary = rs.getString("salary");
                String work_place = rs.getString("work_place");

                String del_flag = rs.getString("del_flag");

                Integer checkstate = rs.getInt("checkstate");
                String checkstatecontent = rs.getString("checkcomment");

                Integer invalid = rs.getInt("cancel");
                PreachCloud preachCloud = new PreachCloud();

                Date createDate = new Date(rs.getTimestamp("create_date").getTime());
                if (rs.getTimestamp("update_date") != null) {
                    Date updateDate = new Date(rs.getTimestamp("update_date").getTime());
                    preachCloud.setUpdateTime(updateDate);
                }


                preachCloud.setHits(hits);
                preachCloud.setInvalid(invalid);
                preachCloud.setCreateTime(createDate);

                preachCloud.setOldId(oldId);
                preachCloud.setTitle(title);

                preachCloud.setHoldTime(holddate);

                preachCloud.setCompanyName(companyName);
                preachCloud.setHoldTime(holddate);

                if (salary != null && salary.contains("~") && !salary.contains("面议")) {
                    preachCloud.setSalaryType("0");
                    // 小写转换
                    salary = salary.toLowerCase()
                            .replaceAll("\\.", "")
                            .replaceAll("\\+", "")
                            .replaceAll("&middot;", "")
                            .replaceAll(" ", "");
                    log.info(salary);
                    // 数据转换
                    if (salary.contains("k")) {
                        salary = salary.replaceAll("k", "000");
                    } else if (salary.contains("万")) {
                        salary = salary.replaceAll("万", "0000");
                    } else if (salary.contains("元")) {
                        salary = salary.replaceAll("元", "");
                    } else if (salary.contains("w")) {
                        salary = salary.replaceAll("w", "0000");
                    }
                    String[] array = salary.split("~");
                    String min = array[0].trim();
                    String max = array[1].trim();
                    if (max.contains("不等") || max.contains("以上")) {
                        max = min;
                    }
                    preachCloud.setSalaryMin(Integer.parseInt(min));
                    preachCloud.setSalaryMax(Integer.parseInt(max));

                } else if ("面议".equals(salary)) {
                    preachCloud.setSalaryType("1");
                } else if(salary != null && salary.contains("面议")) {
                    preachCloud.setSalaryType("1");
                } else if(salary == null) {
                    preachCloud.setSalaryType("0");
                } else {
                    // 异常数据
                    preachCloud.setSalaryType("2");
                }


                preachCloud.setDeleted("0".equals(del_flag) ? 0 : 1);
                preachCloud.setState(getState(checkstate));

                preachCloud.setContent(comment != null ? comment.replaceAll("/ueditor/jsp/upload", contentUrl + "/ueditor/jsp/upload") : "");
                preachCloud.setJobName(jobname);
                preachCloud.setInvalid(cancel);
                preachCloud.setNumber(recruitnumber);
                preachCloud.setArea(work_place);
                preachCloud.setMajors(majors);
                preachCloud.setEducation(education);
                preachCloud.setRecruitContact(linkman);
                preachCloud.setRecruitMobile(tel);
                preachCloud.setRecruitWebsite(recruiturl);
                preachCloud.setEmail(email);
                preachCloud.setHoldUrl(holdurl);
                preachCloud.setStateContent(checkstatecontent);

                if (companyid != null) {
                    Company company = getCompanyId(companyList, companyid);
                    if (company != null) {
                        preachCloud.setCompanyId(company.getId());
                    } else {
                        preachCloud.setCompanyId(0);
                    }
                }

                i++;
                log.info("空中宣讲会信息：{} 数量：{} 个", title, i);
                if (preachCloudService.save(preachCloud)) {
                    log.info("空中宣讲会信息：{} 数量：{} 个", title, i);
                }
            }
            long overTime = System.currentTimeMillis();
            long finishTime = (overTime - beginTime) / 1000;
            log.info("完成时间 : {} 分", finishTime);
            return JsonResult.ok(String.format("完成时间 : %s 分", finishTime));
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return JsonResult.ok();
    }


    /**
     * 查询所有单位信息
     *
     * @return
     */
    private List<Company> getCompanyList() {
        return companyService.list();
    }

    /**
     * 查询原始
     *
     * @return
     */
    private Company getCompanyId(List<Company> companyList, String oldId) {
        for (Company company : companyList) {
            if (oldId.equals(company.getOldId())) {
                return company;
            }
        }
        return null;
    }

    private String getState(Integer state) {
        switch (state) {
            case 0:
                return "0";
            case 1:
                return "1";
            case -1:
                return "2";
            case -2:
                return "3";
            default:
                return "";
        }
    }

}
